import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import StatisticsCard from '@/components/StatisticsCard/Index';
import { downloadOrderSaleDataForDetail, getOrderSaleDataForDetail } from '@/services/report/api';
import { isNull, showMsg } from '@/utils/utils';
import { ConsoleSqlOutlined } from '@ant-design/icons';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import MyPagination from '@/components/MyPagination';
import ProTable from '@ant-design/pro-table';
import { Button, DatePicker, FormInstance } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import './style.less';


const StockList: React.FC = (props: any) => {
  const { start, end, handleType } = props.location.query;
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [detail, setDetail] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [current, setCurrent] = useState(1); // 当前页
  const [total, setTotal] = useState(20); // 总记录数

  useEffect(() => {
    formRef.current?.setFieldsValue({
      rangedate: [moment(start), '-', moment(end)],
      handleType
    });
    formRef.current?.submit();
  }, [])

  const getList = async (params: any) => {
    try {
      params.begin_date_str = moment(params.rangedate[0]).format('YYYYMMDD');
      params.end_date_str = moment(params.rangedate[2]).format('YYYYMMDD');
      params.current = current;
      params.pageSize = 20;
      const data = await getOrderSaleDataForDetail(params);
      setDetail(data);
      setSearchParams(params);
      if (current === 1) {
        setTotal(data.sum_record_num)
      }
      return {
        data: data.record_list,
        success: true,
        total: data.sum_record_num
      }
    } catch (error) {
      showMsg(error?.data?.errmsg); 
      return {
        data: [],
        success: true,
        total: 0
      };
    }
  }

  const download = async () => {
    setLoading(true);
    await downloadOrderSaleDataForDetail(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  const onChange = (page) => {
    setCurrent(page)
    actionRef.current.reload();
  }

  // 合并行
  const hb = (value: any, record: any, index: number, key?: string, valueEnum?: Object) => {
    const obj: any = {
      children: valueEnum || value,
      props: {},
    };
    if (index > 0) {
      const before = detail.record_list[index - 1]; // 前一行
      if (before?.orderId === record.orderId && before[key] === record[key]) {
        // 与前一行相同，那当前就是被合并的行
        obj.props.rowSpan = 0;
        return obj;
      }
    }
    // 计算需要合并多少行
    const afterDataArr = detail.record_list.slice(index + 1);
    let count = 0;
    for (let i = 0, len = afterDataArr.length; i < len; i++) {
      const tmp = afterDataArr[i];
      if (tmp.orderId === record.orderId && tmp[key] === record[key]) {
        count += 1;
      } else {
        break;
      }
    }
    if (count === 0) {
      return obj;
    }
    obj.props.rowSpan = count + 1;
    return obj;
  }

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '下单周期',
      dataIndex: 'rangedate',
      valueType: 'dateRange',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{ gap: 2 }}>
          <DatePicker allowClear={false} />
          <span style={{ padding: '0 5px' }}>-</span>
          <DatePicker allowClear={false} />
        </ProFormFieldSet>
        );
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderId',
      width: 120,
      search: false,
      render: (value, record, index) => hb(value, record, index, 'orderId')
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      width: 140,
      search: false,
      render: (value, record, index) => hb(value, record, index, 'createTime')
    },
    {
      title: '交易类型',
      dataIndex: 'handleType',
      valueType: 'select',
      width: 60,
      valueEnum: {
        'P': '交易',
        'R': '退款',
      },
      render: (value, record, index) => hb(record.handleType, record, index, 'handleType', value)
    },
    {
      title: '交易渠道',
      dataIndex: 'createChannel',
      valueType: 'select',
      width: 70,
      valueEnum: {
        O: '一次性订单',
        P: '计划订单',
        S: '小程序',
      },
      render: (value, record, index) => hb(record.createChannel, record, index, 'createChannel', value)
    },
    {
      title: '结算状态',
      dataIndex: 'orderStatus',
      hideInSearch: true,
      width: 60,
      render: (value, record, index) => hb(value, record, index, 'orderStatus')
    },
    {
      title: '结算状态',
      dataIndex: 'order_status',
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        C: '已开单',
        W: '结算中',
        P: '已结算',
        R: '已退款',
        U: '待退款'
      }
    },
    {
      title: '结算单号',
      dataIndex: 'settleNo',
      width: 120,
      search: false,
      render: (value, record, index) => hb(value, record, index, 'settleNo')
    },
    {
      title: '订单金额',
      dataIndex: 'totalPrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false,
      render: (value, record, index) => hb(value, record, index, 'totalPrice')
    },
    {
      title: '订单折扣',
      dataIndex: 'discountRatio',
      width: 60,
      align: 'right',
      search: false,
      render: (value, record, index) => hb(value, record, index, 'discountRatio')
    },
    {
      title: '结算金额',
      dataIndex: 'settlePrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false,
      render: (value, record, index) => hb(value, record, index, 'settlePrice')
    },
    {
      title: '商品编号',
      dataIndex: 'goodsid',
      width: 120,
      search: false
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 120,
      search: false
    },
    {
      title: '商品规格',
      dataIndex: 'specsName',
      width: 120,
      search: false
    },
    {
      title: '数量',
      dataIndex: 'goodsNum',
      width: 60,
      align: 'right',
      search: false

    },
    {
      title: '单价',
      dataIndex: 'goodsPrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      width: 50,
      align: 'right',
      search: false
    },
    {
      title: '结算价',
      dataIndex: 'discountPrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    }
  ];

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
    ]} title='订单销售明细' breadcrumb={{}} onBack={() => history.goBack()}>
      <ProTable<STOCKGOODSAPI.GoodsItem, STOCKGOODSAPI.GoodsItem & COMMON.PageParams>
        formRef={formRef}
        actionRef={actionRef}
        rowKey={record => `${record.orderId}_${Math.random(0, 9999999)}`}
        bordered
        manualRequest
        search={{
          defaultCollapsed: false,
          collapseRender: () => { return '' },
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              ...dom,
              <PermissionControl action_id="700701004">
                <Button key="export" type="primary" loading={loading} onClick={download}>导出报表</Button>
              </PermissionControl>
            ]
          }
        }}
        request={getList}
        options={false}
        columns={columns}
        scroll={{ x: 1600, y: window.innerHeight - 100 }}
        tableExtraRender={(_, data) => (
          <div className='StatisticsCard' style={{ background: '#fff', padding: 12 }}>
            <div style={{ marginBottom: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <StatisticsCard iconType="database" title="周期销售单数" number={detail.totalOrderNum} />
              <StatisticsCard title="周期订单总额" number={`￥${detail.totalOrderPrice}`} />
              <StatisticsCard iconType="database" title="周期退款单数" number={detail.totalRefundOrderNum} />
              <StatisticsCard style={{ marginRight: 0 }} title="周期退款总额" number={`￥${detail.totalRefundOrderPrice}`} />
            </div>
          </div>
        )}
        pagination={false}
        // 搜索前把分页重置
        beforeSearchSubmit={(e) => {
          setCurrent(1);
          return e;
        }}
      />
      <MyPagination
        current={current}
        pageSize={20}
        onChange={onChange}
        total={total}
      />
    </PageContainer>
  );
};
export default StockList;
